package UIFree.controls
{
	import UIFree.uif_component;
	import UIFree.uif_ecomponent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	
	public class uif_ratingStars extends uif_ecomponent {
		private var _smask			: uif_stars;
		private var _rate			: uif_ecomponent;
		private var _percent		: Number;
		private var _editMode		: Boolean;
		private var _steps			: int;
		
		public function uif_ratingStars(parent:uif_component, a_steps: int=5, ax:int=0, ay:int=0, awidth:int=0, aheight:int=0, styleClass:Object='') {
			_steps = a_steps;
			super(parent, ax, ay, awidth, aheight, styleClass);
			createComponents();
		}
		
		protected function createComponents(): void {
			var inner: Rectangle = getInner();
			_smask = new uif_stars(this, _steps, inner.x, inner.y, inner.width, inner.height, style.mask);
			_rate = new uif_ecomponent(this, inner.x, inner.y, inner.width, inner.height, style.rateline);
			_rate.mask = _smask;
		}

		public function get percent(): Number {
			return _percent;
		}
		
		public function set percent(a_percent: Number): void {
			var inner: Rectangle = getInner();
			_percent = a_percent;
			_rate.width = inner.width * _percent;
			hint = getCurrentHint();
		}
		
		protected function getCurrentHint(): String {
			return Math.round(_percent * 100) + '%';
		}
		
		public function get editMode(): Boolean {
			return _editMode;
		}

		public function set editMode(a_editMode: Boolean): void {
			if (_editMode != a_editMode) setEditMode(a_editMode);
		}
		
		protected function setEditMode(a_editMode: Boolean): void {
			_editMode = a_editMode;
			if (_editMode) {
				addEvent(MouseEvent.MOUSE_MOVE, doMove);
				addEvent(MouseEvent.CLICK, doClick);
			} else {
				removeEventListener(MouseEvent.MOUSE_MOVE, doMove);
				removeEventListener(MouseEvent.CLICK, doClick);
			}
		}
		
		protected function doMove(e: MouseEvent): void {
			var p: Number = e.localX / width;
			if (p < 0) p=0;
			else if (p > 1) p=1;
			percent = Math.ceil(p * _steps) / _steps;
		}
		
		public function get steps(): int {
			return _steps;
		}
		
		protected function doClick(e: MouseEvent): void {
			setEditMode(false);
			dispatchEvent(new Event(Event.CHANGE));
		}
	}
}